<?php

namespace common\models;

use common\base\BaseBackendActiveRecord;
use Cm;

/**
 * This is the model class for table "user_rebate".
 *
 * @property int $uid 用户ID
 * @property int $balance 余额
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class UserBalance extends BaseBackendActiveRecord
{
    const  USER_BALANCE_KEY = 'user_balance:';
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user_balance';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['created_at','updated_at'], 'safe'],
            [['uid'], 'integer'],
            [['balance'],'number']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'uid' => 'uid',
            'balance' => 'balance',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    //余额缓存
    public static function getBalance($uid){
        $model = self::findOne(['uid'=>$uid]);
        if(!Cm::$redis->hExists(self::USER_BALANCE_KEY,$uid)){
            if($model){
                $balance=$model->balance;
                Cm::$redis->hSet(self::USER_BALANCE_KEY,$uid,$balance);
                return $balance;
            }else{
                $model=(new self());
                $model->uid=$uid;
                if(!$model->save())throw new \Exception('钱包添加异常');
                return 0;
            }
        }else{
            return Cm::$redis->hGet(self::USER_BALANCE_KEY,$uid);
        }
    }
    //余额加
    public static function addBalance($uid,$add_money){
        $balance=sprintf("%.2f",self::getBalance($uid)+$add_money);
        $model = self::findOne(['uid'=>$uid]);
        $model->balance=$balance;
        if(!$model->save())throw new \Exception('钱包操作异常');
        Cm::$redis->hSet(self::USER_BALANCE_KEY,$uid,$balance);
    }
    //余额扣除
    public static function DeductBalance($uid,$deduct_money){
        $balance=sprintf("%.2f",self::getBalance($uid)-$deduct_money);
        if($balance<0)throw new \Exception('钱包余额不足');
        $model = self::findOne(['uid'=>$uid]);
        $model->balance=$balance;
        if(!$model->save())throw new \Exception('钱包操作异常');
        Cm::$redis->hSet(self::USER_BALANCE_KEY,$uid,$balance);
    }

}
